package cn.engage.ekcc.exception;

import cn.engage.ekcc.result.JsonResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     *
     * 捕获全局异常
     * @return
     */
    @ExceptionHandler(Exception.class)
    public JsonResult everyExceptionHandler(Exception e){
        e.printStackTrace();
        return JsonResult.error(GlobalExceptionEnum.ERROR);
    }

    /**
     *
     * 捕获自定义异常
     * @return
     */
    @ExceptionHandler(GobalException.class)
    public JsonResult everyExceptionHandler(GobalException e){
        return JsonResult.error(e);
    }

    /**
     *
     * JSR303校验捕获异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JsonResult everyExceptionHandler(MethodArgumentNotValidException e){
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error ->{
                stringBuilder.append(error.getDefaultMessage()).append(";");
        });
        e.printStackTrace();
        return JsonResult.error(String.valueOf(stringBuilder),GlobalExceptionEnum.COMMON_PARAM_JSR303_ERROR.getCode());
    }
}
